package org.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

/*This activity renders all the details such as related books and info of a 
 * user from the remote database.
 * Student details means all the books which he may have scanned and put then
 * for sale in the application.
 * */

public class GetSingleBookAndStudentDetailsActivity extends Activity {
	private TextView book1, book2, book3, book4, book5;
	private String CourseNumber = "", ISBN = "", CourseNumber1 = "";;
	private TextView textHeading, numberOfRecordsTextView;
	private String[] email = new String[10];
	private String[] phone = new String[10];
	int numberOfRecords = 0;
	private String Student[] = new String[10];

	int counter = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		String result = "";
		super.onCreate(savedInstanceState);

		setContentView(R.layout.getsinglebookandstudentdetailslayout);

		book1 = (TextView) findViewById(R.id.book1);
		book2 = (TextView) findViewById(R.id.book2);
		book3 = (TextView) findViewById(R.id.book3);
		book4 = (TextView) findViewById(R.id.book4);
		book5 = (TextView) findViewById(R.id.book5);

		textHeading = (TextView) findViewById(R.id.textHeading);
		numberOfRecordsTextView = (TextView) findViewById(R.id.numberOfRecords);

		Bundle extras = getIntent().getExtras();

		if (extras == null) {
			return;
		}
		CourseNumber = (String) extras.getSerializable("CourseNumber");
		CourseNumber1 = (String) extras.getSerializable("CourseNumber1");
		ISBN = (String) extras.getSerializable("ISBN");

		String flag = (String) extras.getSerializable("flag");

		textHeading.setText("Details for ISBN: " + ISBN);
		
		String[] lines = CourseNumber.split(System
				.getProperty("line.separator"));

		String url1 = lines[0].substring(7, lines[0].length() - 1);

		if (flag.equals("0"))
			ISBN = url1;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("ISBN", ISBN));

		try {
			//HTTP request sent to remote database for rendering all the books associated with a particulas 
			//user
			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://hci.cs.sfsu.edu/~fall2010.03/Includes/GetBookAndStudentDetailsGivingISBN.php");
			httppost.setEntity(new UrlEncodedFormEntity(postParameters));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();

			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		try {
			JSONArray jArray = new JSONArray(result);
			String ID = null;

			for (int i = 0; i < jArray.length(); i++) {
				numberOfRecords++;
				JSONObject json_data = jArray.getJSONObject(i);
				Log.i("log_tag", " Title: " + json_data.getString("Title")
						+ ", Student_ID: " + json_data.getString("Student_ID")
						+ ", Book_Price: " + json_data.getString("Book_Price"));

				ID = json_data.getString("Student_ID");

				numberOfRecordsTextView.setText(numberOfRecords
						+ " records found");


				String result1 = "";
				ArrayList<NameValuePair> postParameters1 = new ArrayList<NameValuePair>();
				postParameters1.add(new BasicNameValuePair("ID", ID));

				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(
						"http://hci.cs.sfsu.edu/~fall2010.03/Includes/GetStudentDetailsGivingID.php");
				try {
					httppost
							.setEntity(new UrlEncodedFormEntity(postParameters1));

					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();

					// convert response to s
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();

					result1 = sb.toString();
				} catch (Exception e) {
					Log.e("log_tag", "Error converting result " + e.toString());
				}

				try {
					JSONArray jArray1 = new JSONArray(result1);

					for (int i1 = 0; i1 < jArray1.length(); i1++) {
						JSONObject json_data1 = jArray1.getJSONObject(i1);
						Log.i("log_tag", " Name: "
								+ json_data1.getString("Name") + ", Email: "
								+ json_data1.getString("Email") + ", Phone: "
								+ json_data1.getString("Phone"));

						Student[counter] = "Name: "
								+ json_data1.getString("Name") + "\nEmail: "
								+ json_data1.getString("Email") + "\nPhone: "
								+ json_data1.getString("Phone")
								+ "\nBook Price: $"
								+ json_data.getString("Book_Price");
						email[counter] = json_data1.getString("Email");
						phone[counter] = json_data1.getString("Phone");

						counter++;
					}

				} catch (JSONException e) { 
											
					System.out.println("NO RECORDS FOUND");
					System.out.println("Error got: " + e.getMessage());
				}

			}

		} catch (JSONException e) { 
									
			System.out.println("NO RECORDS FOUND");
		}

		for (int i = 0; i < counter; i++)
			System.out.println(Student[i]);

		book1.setText(Student[0]);
		book2.setText(Student[1]);
		book3.setText(Student[2]);
		book4.setText(Student[3]);
		book5.setText(Student[4]);
	}
	
	//Onclick methods for books in the recods, also asks user to delete a particular book 
	//from the database if that book is sold

	public void onClick1(View view) throws Exception {
		Intent i = new Intent(this, MakeCallSendEmailActivity.class);
		i.putExtra("email", email[0]);
		i.putExtra("phone", phone[0]);
		i.putExtra("Student", Student[0]);

		startActivity(i);
	}

	public void onClick2(View view) throws Exception {
		Intent i = new Intent(this, MakeCallSendEmailActivity.class);
		i.putExtra("email", email[1]);
		i.putExtra("phone", phone[1]);
		i.putExtra("Student", Student[1]);

		startActivity(i);
	}

	public void onClick3(View view) throws Exception {
		Intent i = new Intent(this, MakeCallSendEmailActivity.class);
		i.putExtra("email", email[2]);
		i.putExtra("phone", phone[2]);
		i.putExtra("Student", Student[2]);

		startActivity(i);
	}

	public void onClick4(View view) throws Exception {
		Intent i = new Intent(this, MakeCallSendEmailActivity.class);
		i.putExtra("email", email[3]);
		i.putExtra("phone", phone[3]);
		i.putExtra("Student", Student[3]);

		startActivity(i);
	}

	public void onClick5(View view) throws Exception {
		Intent i = new Intent(this, MakeCallSendEmailActivity.class);
		i.putExtra("email", email[4]);
		i.putExtra("phone", phone[4]);
		i.putExtra("Student", Student[4]);

		startActivity(i);
	}

	//the back button functionality
	public void Back(View view) throws Exception {
		Intent i = new Intent(this, test.class);
		i.putExtra("CourseNumber", CourseNumber1);
		startActivity(i);
	}
	
	public void test1(View view) throws Exception {
		Intent i = new Intent(this, test1.class);
		i.putExtra("CourseNumber", CourseNumber);
		startActivity(i);
	}

}